using System;
using Blog.Core.Entities;
using Blog.Infrastructure.DataAcces.Repositories.Abstractisations;
using Blog.Infrastructure.DataAcces.Services.Abstractisations;

namespace Blog.Infrastructure.DataAcces.Services.Implementations
{
    public class MembershipService:IMembershipService
    {
        protected IUserRepository userRepository;

        public MembershipService(IUserRepository userRepository)
        {
            this.userRepository = userRepository;
        }

        public bool ValidateUser(string userName, string password)
        {
            var user = userRepository.GetByLogin(userName);

            return UserMatchCredentials(user, password);
        }

        

        public void CreateUser(string userName, string password, string email)
        {
            var user = new User() {LoginName = userName, Password = password, Email = email};
            userRepository.Save(user);
        }

        public bool ChangePassword(string userName, string oldPassword, string newPassword)
        {
            var user = userRepository.GetByLogin(userName);

            if (UserMatchCredentials(user, oldPassword))
            {
                user.Password = newPassword;
                userRepository.Save(user);
                return true;
            }
          
            return false;
        }

        private bool UserMatchCredentials(User user, string password)
        {
            return user != null && user.Password == password;
        }
    }
}